<template>
  <div class="liteflow-breadcrumb" v-if="trail.length">
    <ul class="liteflow-breadcrumb__list">
      <li class="liteflow-breadcrumb__item liteflow-breadcrumb__item--root" @click="handleRootClick">
        <span class="liteflow-breadcrumb__icon">🏠</span>
      </li>
      <li
        v-for="item in trail"
        :key="item.id"
        class="liteflow-breadcrumb__item"
        @click="() => handleSelect(item)"
      >
        <img class="liteflow-breadcrumb__icon" :src="item.icon" alt="" />
        <span>{{ item.label }}</span>
      </li>
    </ul>
  </div>
</template>

<script>
import { defineComponent, ref, watch, onMounted, onBeforeUnmount } from 'vue';
import { useGraphContext } from '../composables/useGraph.js';
import { getIconByType } from '../core/index.js';

export default defineComponent({
  name: 'LiteFlowBreadcrumb',
  setup() {
    const { flowGraph } = useGraphContext();
    const selectedModel = ref(null);
    const trail = ref([]);
    const disposers = [];

    const buildTrail = () => {
      const graph = flowGraph.value;
      if (!graph) {
        trail.value = [];
        return;
      }

      const nodes = graph.getSelectedCells().filter((cell) => cell.isNode());
      const parents = [];

      if (selectedModel.value || nodes.length === 1) {
        const currentModel =
          selectedModel.value || nodes[0].getData()?.model;
        let nextModel = currentModel?.proxy || currentModel;
        while (nextModel) {
          if (nextModel.parent) {
            parents.unshift(nextModel);
          }
          nextModel = nextModel.parent;
        }
      }

      trail.value = parents.map((model) => ({
        id: model.id || model.type,
        label: model.type,
        model,
        icon: getIconByType(model.type),
      }));
    };

    const handleForceUpdate = () => {
      selectedModel.value = null;
      buildTrail();
    };

    const handleModelSelect = (model) => {
      selectedModel.value = model;
      buildTrail();
    };

    const handleSelectionChange = () => {
      if (!selectedModel.value) {
        buildTrail();
      }
    };

    const handleSelect = (item) => {
      const graph = flowGraph.value;
      if (!graph) return;
      graph.cleanSelection();
      graph.select(item.model.getNodes());
      selectedModel.value = item.model;
      graph.trigger('model:select', item.model);
      buildTrail();
    };

    const handleRootClick = () => {
      const graph = flowGraph.value;
      if (!graph) return;
      graph.cleanSelection();
      selectedModel.value = null;
      buildTrail();
    };

    const bindGraph = (graph) => {
      if (!graph) return;
      buildTrail();
      graph.on('settingBar:forceUpdate', handleForceUpdate);
      graph.on('model:select', handleModelSelect);
      graph.on('selection:changed', handleSelectionChange);
      disposers.push(() =>
        graph.off('settingBar:forceUpdate', handleForceUpdate),
      );
      disposers.push(() => graph.off('model:select', handleModelSelect));
      disposers.push(() =>
        graph.off('selection:changed', handleSelectionChange),
      );
    };

    onMounted(() => {
      if (flowGraph.value) {
        bindGraph(flowGraph.value);
      }
      watch(
        () => flowGraph.value,
        (graph, _, onCleanup) => {
          disposers.splice(0).forEach((dispose) => dispose());
          if (graph) {
            bindGraph(graph);
          }
          onCleanup(() => {
            disposers.splice(0).forEach((dispose) => dispose());
          });
        },
        { immediate: false },
      );
    });

    onBeforeUnmount(() => {
      disposers.splice(0).forEach((dispose) => dispose());
    });

    return {
      trail,
      handleSelect,
      handleRootClick,
    };
  },
});
</script>

<style lang="less" scoped>
.liteflow-breadcrumb {
  position: absolute;
  left: 24px;
  bottom: 24px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 20px;
  padding: 6px 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  pointer-events: auto;
}

.liteflow-breadcrumb__list {
  display: flex;
  align-items: center;
  gap: 8px;
  list-style: none;
  padding: 0;
  margin: 0;
}

.liteflow-breadcrumb__item {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  padding: 4px 8px;
  border-radius: 16px;
  font-size: 13px;
  color: #2f3640;
  cursor: pointer;
  transition: background 0.2s ease;

  &:hover {
    background: rgba(24, 144, 255, 0.15);
  }

  &--root {
    font-size: 14px;
  }
}

.liteflow-breadcrumb__icon {
  width: 16px;
  height: 16px;
}
</style>

